package cn.fufeiii.bt.demo.springcache;

import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

/**
 * @author FuFei
 */
@Slf4j
@Service
public class CacheService {

    @Cacheable(cacheManager = SpringCacheConfig.REDIS, cacheNames = "rand", key = "#key")
    public String randString(String key) {
        log.info("randString -> 进入逻辑体{}", key);
        return RandomUtil.randomString(5);
    }

    @Caching(
            cacheable = @Cacheable(cacheManager = SpringCacheConfig.REDIS, cacheNames = "rand", condition = "!#flush", unless = "#result == null", key = "#key"),
            put = @CachePut(cacheManager = SpringCacheConfig.REDIS, cacheNames = "rand", condition = "#flush", key = "#key")
    )
    public Integer randInteger(Boolean flush, String key) {
        log.info("randInteger -> 进入逻辑体{}-{}", flush, key);
        return RandomUtil.randomInt();
    }

    @CacheEvict(cacheManager = SpringCacheConfig.REDIS, cacheNames = "rand", key = "#key")
    public void removeCache(String key) {
        log.info("removeCache -> 进入逻辑体{}", key);
    }

}
